package gozerocommon

import (
	"net/http"

	"gitee.com/bioinnobio/go-zero-common/xerr"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"
)

type Body struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data,omitempty"`
}

func Response(w http.ResponseWriter, resp interface{}, err error) {

	var body Body
	if err != nil {
		var code int64 = -1
		var msg string
		st, ok := status.FromError(err)
		if ok {
			msg = st.Message()
		} else {
			msg = err.Error()
		}

		errdata, ok := err.(xerr.BioError)

		if ok {
			code = errdata.GetErrCode()
			msg = errdata.GetErrMsg()
		}
		body.Code = int(code)
		body.Msg = msg
	} else {
		body.Msg = "ok"
		body.Data = resp
	}
	httpx.OkJson(w, body)
}
